﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.UI;
using WebDiagnostics.Extensions;

namespace WebDiagnostics.Diagnosers.Routing
{
    public class RouteDiagnosis : Diagnosis
    {
        public IEnumerable<Route> Routes { get; set; }

        public override void Render(System.IO.TextWriter writer)
        {
            var htmlWriter = new HtmlTextWriter(writer);

            htmlWriter.RenderHeader(2, "Registered Routes");

            htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "scrollable");
            htmlWriter.RenderBeginDiv("scrollable");

            htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "registered-routes grid");
            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Table);

            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Thead);
            htmlWriter.WriteLine("<tr> <th>Url</th> <th>Handler</th> </tr>");
            htmlWriter.RenderEndTag();

            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tbody);
            foreach (var route in Routes)
                RenderRoute(route, htmlWriter);
            htmlWriter.RenderEndTag();

            htmlWriter.RenderEndTag();
            htmlWriter.RenderEndTag();
        }

        private void RenderRoute(Route route, HtmlTextWriter htmlWriter)
        {
            IEnumerable<string> defaults =
                (route.Defaults ?? new RouteValueDictionary())
                    .Select(x => string.Format("{0}: {1}", x.Key, GetRoutingDefaultString(x.Value)));

            if(defaults.Any())
            {
                string defaultText = string.Join("\n  ", defaults);
                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Title, defaultText);
            }

            htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "registered-route");
            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
            
            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td);
            htmlWriter.Write(route.Url);
            htmlWriter.RenderEndTag();

            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td);
            var fullHandlerName = route.RouteHandler.ToString();
            var shortHandlerName = fullHandlerName.ShortenFullTypeName();
            htmlWriter.Write("<span title='{0}'>{1}</span>", fullHandlerName, shortHandlerName);
            htmlWriter.RenderEndTag();

            htmlWriter.RenderEndTag();
        }

        private string GetRoutingDefaultString(object @default)
        {
            if (@default == UrlParameter.Optional)
                return "[Optional]";

            return (@default ?? string.Empty).ToString();
        }
    }
}